﻿
using System;
using System.Windows.Forms;

namespace CatEars.Core.UI.Displays.Forms
{
    /// <summary>
    /// 使用Label显示进度
    /// </summary>
    public class LabelUpdateByTimeSpan
    {
        /// <summary>
        /// 使用Label显示进度
        /// </summary>
        /// <param name="label">Label控件</param>
        /// <param name="msSpan">刷新间隔</param>
        public LabelUpdateByTimeSpan(Label label, int msSpan = 1000)
        {
            _label = label;
            _msSpan = msSpan;
        }

        /// <summary>
        /// 控件
        /// </summary>
        private Label _label;

        /// <summary>
        /// 上次刷新时间
        /// </summary>
        private DateTime m_dteLastDisplay = DateTime.Now;

        /// <summary>
        /// 时间间隔
        /// </summary>
        private int _msSpan = 1000;

        /// <summary>
        /// 显示文本
        /// </summary>
        /// <param name="strText">要显示的文本</param>
        /// <param name="blnForce">强制显示</param>
        public void ShowText(string strText, bool blnForce)
        {
            if (_label.Text == strText)
            {
                return;
            }
            if (!blnForce)
            {
                var ts = (DateTime.Now - m_dteLastDisplay).TotalMilliseconds;
                if (ts < _msSpan)
                {
                    return;
                }
            }
            _label.Invoke((EventHandler)delegate
            {
                _label.Text = strText;
                m_dteLastDisplay = DateTime.Now;
                Application.DoEvents();
            });
        }
    }
}
